package com.itmk.web.companyInfo.controller;

import com.itmk.utils.JWTUtils;
import com.itmk.utils.Result;
import com.itmk.utils.UID;
import com.itmk.web.adminInfo.entity.ForjInfo;
import com.itmk.web.companyInfo.entity.*;
import com.itmk.web.companyInfo.service.CompanyService;
import com.itmk.web.userInfo.entity.TokenUUID;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/company")
public class CompanyController {

    @Autowired
    private CompanyService companyService;

    //boss企业继续认证
    @RequestMapping("/updateBossNameAndIden")
    @ResponseBody
    public Result continueLogin(HttpServletRequest request,@RequestBody Company company){
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }
        //更新名字和身份证
        Boolean res = companyService.updateNameAndIden(company.getRealname(), company.getLinkmanIden(),uuid);
        if(res){
            return Result.ok("身份认证成功");
        }
        return Result.error("身份认证失败");

    }

    /**
     * 获取公司信息
     * @param request
     * @return
     */
    @RequestMapping("/getBossInfo")
    @ResponseBody
    public Result getCompanyInfo(HttpServletRequest request){
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        Company company = companyService.getCompanyInfo(uuid);

        return Result.ok().put("data",company);
    }

    /**
     * 修改公司logo
     * @param request
     * @param pic
     * @return
     */
    @RequestMapping("/updateBossProfile")
    @ResponseBody
    public Result updateCompanyLogo(HttpServletRequest request, MultipartFile pic){

        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        // 检查目录是否存在，如果不存在则创建
        String pre1 = "E:\\file\\images\\companyLogo\\";
        File directory = new File(pre1);
        if (!directory.exists()) {
            directory.mkdirs();
        }


        if(pic!=null){
            //判断图片是否存在
            String exist = companyService.checkFile(uuid);
            if (exist!=null) {
                String pre = "E:\\file\\images\\companyLogo\\";

                File file = new File(pre+exist);
                if(file.delete()){
                    System.out.println("删除成功");
                }else{
                    System.out.println("删除失败");
                    return Result.error("替换原有图片操作失败");
                }
            }

            //file重命名
            String originalFilename = pic.getOriginalFilename();
            String ext = "."+originalFilename.split("\\.")[1];
            String imageUUID = UUID.randomUUID().toString().replace("-","");
            String fileName = imageUUID+ext;
            //上传图片
//            ApplicationHome applicationHome = new ApplicationHome(this.getClass());
//            String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath()+
//                    "\\src\\main\\resources\\static\\images\\companyLogo\\";
//            String property = System.getProperty("user.dir")+"\\itmk-base-web";
//            String pre = property + "\\target\\classes\\static\\images\\companyLogo\\";
            String pre = "E:\\file\\images\\companyLogo\\";

            companyService.updateLogo(fileName,uuid);
            String path1 = pre+fileName;
            String path = path1.replace("/","\\");
            try {
                pic.transferTo(new File(path));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return Result.ok("修改成功").put("logo",fileName);
        }
        return Result.error("上传图片失败");
    }

    /**
     * 更新公司信息
     * @param request
     * @param company
     * @return
     */
    @RequestMapping("/updateBossInfo")
    @ResponseBody
    public Result updateCompanyInfo(HttpServletRequest request,@RequestBody Company company){

        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        Boolean result = companyService.updateCompanyInfo(company,uuid);
        if(result){
            return Result.ok("修改成功");
        }
        return Result.error("修改失败");
    }

    /**
     * 添加岗位
     * @param request
     * @param jobInfo
     * @return
     */
    @RequestMapping("/addJobInfo")
    @ResponseBody
    public Result addJobInfo(HttpServletRequest request, @RequestBody JobInfo jobInfo){
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        String job_uuid = UID.getUUID();
        jobInfo.setJobUuid(job_uuid);
        Boolean res = companyService.addJobInfo(jobInfo,uuid);
        if(res){
            return Result.ok("成功添加岗位");
        }
        return Result.error("添加岗位失败");
    }

    /**
     * 根据job_uuid删除岗位
     * @param request
     * @param
     * @return
     */
    @RequestMapping("/deleteJobInfo/{job_uuid}")
    @ResponseBody
    public Result deleteJobInfo(HttpServletRequest request,@PathVariable String job_uuid){
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        boolean res = companyService.deleteJobInfo(job_uuid,uuid);
        if(res){
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }


    /**
     * 获取企业所有的岗位
     * @param request
     * @return
     */
    @RequestMapping("/getBossJob")
    @ResponseBody
    public Result allJobByCompany(HttpServletRequest request){
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        List<JobInfo> res = companyService.allCompanyJob(uuid);
        return Result.ok().put("data",res);
    }
    /**
     * 根据job_uuid获取一条job信息
     */
    @RequestMapping("/getOneJob/{job_uuid}")
    @ResponseBody
    public Result getOnJob(HttpServletRequest request,@PathVariable String job_uuid) {
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        JobInfo jobInfo = companyService.getOneJob(job_uuid);
        if(jobInfo!=null){
            return Result.ok().put("data", jobInfo);
        }
        return Result.error("获取数据失败");
    }
    /**
     * 根据skill来获取job信息
     */
    @RequestMapping("/geek/getJobBySkill/{skill}")
    @ResponseBody
    public Result getJobBySkill(HttpServletRequest request,@PathVariable String skill) {
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        List<JobInfo> list = companyService.getJobBySkill(skill,uuid);
        if(list!=null){
            return Result.ok().put("data", list);
        }
        return Result.error("获取数据失败");
    }
    /**
     * 修改job信息
     */

    @RequestMapping("/updateJobInfo")
    @ResponseBody
    public Result updateJobInfo(HttpServletRequest request, @RequestBody JobInfo jobInfo) {
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        boolean res = companyService.updateJobInfo(jobInfo,uuid);
        if(res){
            return Result.ok("修改数据成功");
        }
        return Result.error("修改数据失败");
    }
    /**
     * 岗位被投简历
     */
    @RequestMapping("/geek/addResume")
    @ResponseBody
    public Result addResume(HttpServletRequest request, @RequestBody AddResume addResume) {
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        addResume.setUserInfo_uuid(uuid);
        boolean res = companyService.addResume(addResume);
        if(res){
            return Result.ok("增加简历成功");
        }
        return Result.error("增加简历失败");
    }

    /**
     * 获取投递岗位的所有简历信息
     */
    @RequestMapping("/getAllResume/{job_uuid}")
    @ResponseBody
    public Result getAllResume(HttpServletRequest request,@PathVariable String job_uuid){
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        //获取岗位所有投递简历的用户
        List<String> users = companyService.getAllResume(job_uuid);
        //根据用户来检索pdf版简历
        if(users!=null){
            List<String> resumes = new ArrayList<>();
            for (String user : users) {
                String resume = companyService.getResumePDF(user);
                resumes.add(resume);
            }
            return Result.ok().put("data",resumes);
        }
        return Result.error("当前岗位无用户投递");
    }


    @RequestMapping("/geek/collectJob")
    @ResponseBody
    public Result collectJob(HttpServletRequest request, @RequestBody CollectJob collectJob){
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        collectJob.setUserUuid(uuid);
        Boolean res = companyService.CollectJobs(collectJob);
        Boolean insertCollect = companyService.updateJobCollect(collectJob.getCompanyUuid());
        if(res&&insertCollect){
            return Result.ok("收藏成功");
        }
        return Result.error("收藏失败");
    }

    /**
     * 取消收藏
     * @param request
     * @param
     * @return
     */

    @RequestMapping("/geek/cancelCollectJob")
    @ResponseBody
    public Result cancelCollectJob(HttpServletRequest request, @RequestBody CollectJob collectJob){
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        collectJob.setUserUuid(uuid);
        CollectJob collectJob1 = companyService.getCollect(collectJob);
        collectJob1.setUserUuid(uuid);
        if(collectJob1!=null){
            companyService.cancelCollect(collectJob.getJobUuid(),uuid);
            return Result.ok("取消收藏成功");
        }
        return Result.error("取消收藏失败");
    }

    @RequestMapping("/geek/visitsJob")
    @ResponseBody
    public Result visitsJob(HttpServletRequest request, @RequestBody VisitsJob visitsJob){
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        visitsJob.setUserUuid(uuid);
        Boolean res = companyService.updatejobVisits(visitsJob);
        Boolean insertVisits = companyService.updateBossvisits(visitsJob);
        if(res&&insertVisits){
            return Result.ok("有用户浏览该岗位");
        }
        return Result.error("浏览记录存储失败");
    }

    /**
     * 获得该boss的岗位数目
     * @param
     * @return
     */
    @RequestMapping("/getShow")
    @ResponseBody
    public Result getJobNum(HttpServletRequest request){
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        int res = companyService.getJobNum(uuid);
        Show show = companyService.getShow(uuid);
        show.setPositions(res);
        return Result.ok().put("show",show);
    }

    /**
     * BOSS向用户提交offer
     * @param request
     * @return
     */
    @RequestMapping("/offer")
    @ResponseBody
    public Result offer(HttpServletRequest request,@RequestBody Offer offer){
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = companyService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        offer.setCompanyUuid(uuid);
        companyService.insertOffer(offer);
        companyService.updateOfferNum(uuid);
        return Result.ok("发送offer成功");
    }


    //*********************************************************************************************************************
    //****************************************************岗位推荐**********************************************************
    //*********************************************************************************************************************

    @RequestMapping("/geek/RecommondJob")
    @ResponseBody
    public Result RecommondJob(HttpServletRequest request){
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();
        //获取简历信息，期望城市，期望薪资，期望职位
        ForjInfo forjobhInfo = companyService.getForJobInfo(uuid);
        Salary salary = new Salary();
        String city = forjobhInfo.getCity();
        String forType = forjobhInfo.getForType();
        //根据获得信息来检索获得的岗位
        List<JobInfo> job1 = companyService.getJobFirst(salary,city,forType);
        //根据准备好的推荐算法来检索岗位
        if(job1!=null){
            return Result.ok().put("data",job1);
        }
        return Result.error("查询数据失败");
    }
}
